/*
 * @Author: your name
 * @Date: 2020-05-06 16:15:43
 * @LastEditTime: 2020-10-30 10:26:48
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /yigo/src/RootRedurce.js
 */
import { combineReducers } from 'redux'

import UserInfo from './UserInfoRedurce'
import Order from './OrderRedurce'


export function authUserToken({types}) {
  
  return (state={}, action) => {

    switch (action.type) {

      case 'RefreshToken':  
        return {...state, userInfo:action.userInfo,isFetch:false,}
      default:
        if (state.hasOwnProperty('isFetch')) {
          state.isFetch = false;          
    
          return state
        
        } else {
        
          return {...state,isFetch:true,userInfo:''}
       
        }
    }
  }
}

export function commonReducer(types) {
  return function getData(state = {}, action) {  
    const {
      type,
      response,
      body,
      exit = '',
    } = action;

    let keyFetch, name = exit;
    name = exit.charAt(0).toUpperCase() + name.slice(1);
    keyFetch = `is${name}Fetch`;
    name = name.toLowerCase();

    function returnLastData() {
      if (response) {
        const {
          code,
          data,
          msg
        } = response;

        let resultData;
        //如果需要分页但不符合结构的接口解析一下格式
        switch (type) {
          case 'api/article/findPageSuccess': resultData = data.records;            break;
          case 'api/friend/listSuccess':      resultData = data.list;               break;
          case 'api/user-bill/findProfitPageSuccess': resultData = data.data;       break;
          case 'api/user-bill/findProfitPage/v2Success': resultData = data.data;    break;
          case 'api/user-bill/findSpendPageSuccess': resultData = data.userBillList;break;
          case 'api/money/yejiChangeSuccess':        resultData = data.list;        break;
          default: resultData = data; break;
        }

        if ((body.hasOwnProperty("limit") || body.hasOwnProperty("size")) && 
           body.hasOwnProperty("page") && 
           type === types + 'Success' &&
           body.page > 1) {
  
          resultData = state[`${name}data`].concat(resultData)
        }

        return {
          [`${name}code`]: code,
          [`${name}data`]: resultData,
          [`${name}msg`]: msg,
        }
      }
      return {}
    }

    let obj = returnLastData();
    switch (type) {
      case types:             return { ...state, [keyFetch]: true }
      case types + 'Success':
      case types + 'Failure': return { ...state, ...obj, [keyFetch]: false }
      default:                return state;
    }
  }
}

const RootReducer = combineReducers({
    UserInfo,
    Order
  });
  export default RootReducer;